import os
from time import sleep
from datetime import datetime

from app.util import pluginBase, files

from . import backuper_xrc

class BacuperPanel(backuper_xrc.xrcBackupPanel, pluginBase.PluginMixin):
    """File backuper panel functionality"""

    name = "File backuper"
    _defaultMask = "neo_backup_%Y%m%d_%H%M%S.tar.gz"
    _defaultBackupDirs = ("/home", "/etc")

    def __init__(self, parent, app):
        super(BacuperPanel, self).__init__(parent)
        self._mixinInit(parent, app)

        self.configDefaultVal("mask", self._defaultMask)
        self.configDefaultVal("backupDirs", self._defaultBackupDirs)
        self.configDefaultVal("localBackupDir", files.getDefaultSavedFileDir())

        self._configGuiMap = (
            (self.backupFileDir, "backupDirs"),
            (self.backupPicker, "localBackupDir"),
            (self.backupMask, "mask"),
        )

        self.setControls()

    def dumpData(self):
        """Perform the actual data retrieval and save."""
        # FIXME: If you're having problem with non-english file names
        # than this is a right spot to fix it.
        # (note the `mask` cast to string)
        _outFname = os.path.join(
            self._config["localBackupDir"],
            datetime.now().strftime(str(self._config["mask"])))
        _cmd = ["tar", "czf", "/dev/stdout"]
        _cmd.extend(files.escapeAllArgs(self._config["backupDirs"]))
        _f = file(_outFname, "wb")
        _pipe = self._app.saveFromRemote(_cmd, _f, {"showStderr": True})
        _f.close()

    def OnButton_backupBtn(self, evt):
        """Called upon 'Do backup' button press."""
        self.getControls()
        self.dumpData()

# vim: set sts=4 sw=4 et :
